<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="name"
        name="name"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="tel"
        name="tel"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="address"
        name="address"
        label="地址"
        placeholder="地址"
        :rules="[{ required: true, message: '请填写地址' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="Submit">{{
          text
        }}</van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block type="danger" native-type="button" @click="Del">{{text2}}</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// 引入封装的axios请求
import { api_addlist, api_onelist, api_enitlist , api_Dellist} from "../utlis/index";
export default {
  // 初始化数据
  data() {
    return {
      name: "",
      tel: "",
      address: "",
      id: "",
    };
  },
  // 计算属性
  computed: {
    type() {
      return this.$route.params.type;
    }, 
    text() {
      return this.type === "enit" ? "编辑" : "新增";
    },
    text2() {
      return this.type === "enit" ? "删除" : null;
    },
  },
  // 生命周期
  mounted() {
    const { type } = this.$route.params;
    if (type === "enit") {
      // 获取编辑id
      const { id } = this.$route.query;
      // 调用反显接口
      this.getListDate(id);
    }
  },
  // 事件的集合
  methods: {
    onSubmit(values) {
      if (this.type === "add") {
        // 调用新增接口
        api_addlist({
          name: values.name,
          tel: values.tel,
          address: values.address,
        }).then((res) => {
          // 直接跳转页面
          this.$router.push("/home");
        });
      } else {
        // 调用编辑接口
        api_enitlist(this.id, {
          name: this.name,
          tel: this.tel,
          address: this.address,
        }).then((res) => {
          // 直接跳转页面
          this.$router.push("/home");
        });
      }
    },
    // 删除
    Del()
    {
        api_Dellist(this.id).then(res => 
        {
            // 直接跳转页面
          this.$router.push("/home");
        })
    },
    getListDate(id) {
      api_onelist(id).then((res) => {
        this.name = res.data.onedata.name;
        this.tel = res.data.onedata.tel;
        this.address = res.data.onedata.address;
        this.id = res.data.onedata.id;
      });
    },
  },
};
</script>

<style>
</style>